const router = require('express').Router();
const User = require('../db/user');
const Util = require('../util');
const Album = require('../db/album');
const Article = require('../db/article');
const ArticleClass = require('../db/articleClass');
const Routes = require('../db/routes');
const jwt = require('jsonwebtoken');

let privateKey = 'myweb';

function createToken(data) {
    return jwt.sign({
        exp: Math.floor(Date.now() / 1000) + (60 * 60),
        data: data
    }, privateKey);
}

//签发TOKEN
function checkToken(token, cbk) {
    jwt.verify(token, privateKey, function (err, data) {
        cbk && cbk(err, data)
    });
}

//鉴权
const checkAuth=(req,res,next)=>{
    jwt.verify(req.headers.authorization, privateKey, function (err, data) {
       if(err)
       {
           res.json({
               status:401,
               msg:'鉴权失败，非法请求'
           });
       }else{
           next();
       }
    });
};


//登录
router.post('/vue/login', (req, res) => {
    User.find({username: req.body.username, password: Util.MD(req.body.password)}, (err, data) => {
        if (!err) {
            if (data.length) {
                res.json({
                    status: true,
                    token: createToken(req.body.username),
                    msg: '登录成功'
                })
            } else {
                res.json({
                    status: false,
                    msg: '登录失败,账号或密码错误 '
                })
            }
        } else {
            res.json({
                status: false,
                msg: '系统错误错误信息:' + err
            })
        }
    });
});

//获取用户信息
router.get('/vue/userinfo',checkAuth, (req, res) => {
    checkToken(req.headers.authorization, function (err, data) {
        if (!err) {
            User.find({}, (err, data) => {
                if (!err) {
                    if (data.length) {
                        res.json({
                            status: true,
                            data: {
                                headpic: data[0].headpic,
                                intro: data[0].intro
                            }
                        })
                    }
                } else {
                    res.json({status: false, msg: err})
                }
            });
        } else {
            res.json({
                status: 401,
                msg: '鉴权失败'
            })
        }
    });

});

//编辑用户信息
router.post('/vue/userinfo/edit',checkAuth, (req, res) => {
    User.updateOne({}, {headpic: req.body.headpic, intro: req.body.intro}, function (err, data) {
        if (err) {
            res.json({status: false, msg: err});
        } else {
            res.json({status: true, msg: '修改成功'});
        }
    })

});

/**
 * 文章相关接口
 * */
//获取文章列表
router.get('/vue/article/list',checkAuth, (req, res) => {
    Article.find({}).sort('-addTime').exec((err, data) => {
        res.json(data)
    });
});

//获取文章信息
router.get('/vue/getarticle', (req, res) => {
    let id = req.query.id;
    Article.findOne({_id: id}, (err, data) => {
        if (!err) {
            res.json({
                status: true,
                msg: '收到了请求',
                data: data
            })
        } else {
            res.json({
                status: false,
                msg: err
            })
        }
    });

});

//添加，修改文章
router.post('/vue/editarticle', (req, res) => {
    editArticle(req).then(result => {
        res.json(result)
    })
});
const editArticle = async (req) => {
        let receive = req.body;
        let time = getTime();

        if (!receive.id) {

            if(!receive.cateid){
                return{
                    status:false,
                    msg:'请选择一个文章分类'
                }
            }
            let classInfo=await ArticleClass.findOne({_id:receive.cateid});

            let thisArticle = await new Article({
                addTime:time,
                title: receive.title,
                keywords: receive.keywords,
                desc: receive.desc,
                cateid: receive.cateid,
                publishDate: receive.publishDate,
                detail: receive.detail,
                catename:classInfo.catename
            });

            if (receive.url) {
                thisArticle.seo.url = receive.url;
            } else {
                thisArticle.seo.url = thisArticle._id;
            }
            let thisArticleClass = await ArticleClass.findOne({_id: thisArticle.cateid});
            if(!thisArticleClass)
            {
                return{
                    status:false,
                    msg:'添加失败分类信息不存在'
                }
            }
            thisArticleClass.counter++;


            return addRoute(thisArticle.seo.url, thisArticle._id, 1).then(result => {
                if (result.status) {
                    return thisArticle.save().then(() => {
                        thisArticleClass.save();
                        thisArticle.save();
                        return {
                            status: true,
                            msg: '新增文章成功'
                        }
                    })
                } else {
                    return {
                        status: false,
                        msg: '发布失败,URL已存在'
                    }
                }
            });

        } else {
            if (!receive.cateid) {
                return {
                    status: false,
                    msg: '请选择一个文章分类'
                }
            }
            let thisArticle = await Article.findOne({_id: receive.id});

            if (!thisArticle) {
                return {
                    status: false,
                    msg: '未找到目标文章'
                }
            } else {
                thisArticle.title = receive.title;
                thisArticle.seo.keywords = receive.keywords;
                thisArticle.seo.desc = receive.desc;
                thisArticle.publishDate = receive.publishDate;
                thisArticle.detail = receive.detail;
                thisArticle.lastModified=time;

                let updateCateName=(await ArticleClass.findOne({_id:receive.cateid})).catename;
                if (thisArticle.seo.url !== receive.url) {
                    return addRoute(receive.url, thisArticle._id, 1).then(result => {
                        if (result.status) {
                            updateClassCounter(thisArticle.cateid, receive.cateid).then();
                            thisArticle.cateid = receive.cateid;
                            thisArticle.seo.url = receive.url;
                            thisArticle.catename=updateCateName;
                            thisArticle.save();
                            return {
                                status: true,
                                msg: '修改成功'
                            }

                        } else {
                            return result;
                        }
                    });
                } else {
                    updateClassCounter(thisArticle.cateid, receive.cateid).then();
                    thisArticle.catename=updateCateName;
                    thisArticle.cateid = receive.cateid;
                    await thisArticle.save();
                    return {
                        status: true,
                        msg: '文章更新成功'
                    }
                }
            }
        }
    };

//删除一篇文章
router.post('/vue/deletearticle', (req, res) => {
    delArticle(req.body._id).then(result => {

       res.json(result);
    });
});

const delArticle = async (id) => {
    let article = await Article.findOne({_id: id});
    if (article) {
        let calssInfo=await ArticleClass.findOne({_id:article.cateid});
        calssInfo.counter--;
        await calssInfo.save();
        await article.remove();
        await removeRoute({targetId:id});
        return{
            status:true,
            msg:'删除成功'
        }
    }else{
        return{
            status:false,
            msg:`删除失败，文章不存在`
        }
    }
};

//获取所有文章分类
router.get('/vue/getarticleclass', (req, res) => {
    ArticleClass.find({}, (err, data) => {
        if (!err) {
            res.json(data)

        } else {
            res.json({
                status: false,
                msg: err
            })
        }
    })
});


//添加一个文章分类
router.post('/vue/addarticleclass', (req, res) => {
    addArticleClass(req, res);
});
//删除文章分类
router.post('/vue/delclass', (req, res) => {
    ArticleClass.findOne({_id: req.body.id}, (err, data) => {
        if (!err) {
            if (data.counter <= 0) {
                data.remove();
                res.json({
                    status: true,
                    msg: '删除成功'
                });
                removeRoute({targetId: req.body.id}).then(res => {
                    console.log(res);
                })
            } else {
                res.json({
                    status: false,
                    msg: '删除失败，当前分类下含有文章'
                })
            }

        } else {
            res.json({
                status: false,
                msg: err
            })
        }
    });
});
/**
 * 图库相关接口
 * */
router.get('/vue/albumlib', (req, res) => {
    let page = Number(req.query.page);
    let pageSize = Number(req.query.pageSize);

    Album.find({}).limit(pageSize).skip(pageSize * (page - 1)).exec((err, data) => {

        if (!err) {
            res.json({
                status: true,
                data: data
            })
        } else {
            res.json({
                status: false,
                msg: err
            })
        }
    })
});


//编辑文章分类
const editArticleClass = async (req) => {
    let receive = req.body;
    let catename = receive.catename;

    let currentClass = await ArticleClass.findOne({_id: receive._id});

    let catenameExist = await ArticleClass.findOne({catename: catename});

    if (catenameExist) {
        if (currentClass.catename !== catenameExist.catename) {
            return {
                status: false,
                msg: '分类名称已存在'
            };
        } else {
            return addRoute(receive.url, currentClass._id, 0).then(result => {
                if (result.status) {
                    currentClass.catename = receive.catename;
                    currentClass.url = receive.url;
                    currentClass.isPrivate = receive.isPrivate;

                    return currentClass.save().then(() => {
                        // Article.find({cateid:currentClass._id},(err,data)=>{
                        //     data.forEach(e=>{
                        //         e.catename=receive.catename;
                        //     });
                        //
                        //     data.save();
                        // });

                        return {
                            status: true,
                            msg: '修改分类信息成功！~'
                        }
                    })
                } else {
                    return result;
                }
            })
        }
    } else if (!catenameExist) {
        return addRoute(receive.url, currentClass._id, 0).then(result => {
            if (result.status) {
                currentClass.catename = receive.catename;
                currentClass.url = receive.url;
                currentClass.isPrivate = receive.isPrivate;
                return currentClass.save().then(() => {

                    Article.find({cateid:currentClass._id},(err,data)=>{
                        data.forEach(e=>{
                            e.catename=receive.catename;
                            e.save();
                        });
                        // data.save();
                    });

                    return {
                        status: true,
                        msg: '修改分类信息成功！~'
                    }
                })
            } else {
                return result;
            }
        });
    }
};
router.post('/vue/editclass', (req, res) => {
    editArticleClass(req).then(result => {
        // console.log('响应值')
        // console.log(result)
        res.json(result)
    })
});


//添加文章分类
const addArticleClass = async (req, res) => {
    let receive = req.body;
    let catename = receive.catename;
    let articleClass = await ArticleClass.findOne({catename: catename});
    if (articleClass) {
        res.json({
            status: false,
            msg: '新增失败，分类名称已存在'
        })
    } else {
        let savedArticleClass = await new ArticleClass({
            catename: catename, counter: 0
        }).save();


        savedArticleClass.url = savedArticleClass.id;
        addRoute(savedArticleClass.url, savedArticleClass.id, 0).then(result => {
            if (result.status) {
                savedArticleClass.save();
                res.json({
                    status: true,
                    msg: '新增分类成功'
                })
            } else {
                res.json(result)
            }
        });

    }
};


//添加路由
const addRoute = async (url, targetId, type) => {
    let urlExist = await Routes.findOne({url: url});
    let targetExist = await Routes.findOne({targetId: targetId});
    if (!urlExist) {
        if (targetExist) {
            targetExist.url = url;
            targetExist.type = type;
            targetExist.save();
            return {
                status: true,
                msg: '修改URL成功'
            }
        } else {
            await new Routes({
                url: url,
                targetId: targetId,
                type: type
            }).save();
            return {
                status: true,
                msg: '新增路由成功'
            };
        }
    } else {
        if (urlExist && targetExist && urlExist.targetId === targetExist.targetId) {
            targetExist.url = url;
            targetExist.type = type;
            targetExist.save();
            return {
                status: true,
                msg: '修改URL成功'
            }
        } else {
            return {
                status: false,
                msg: 'URL已存在'
            };
        }

    }
};

//移除路由
const removeRoute = async (opt) => {
    let target = '';
    if (opt.targetId) {
        target = await Routes.findOne({targetId: opt.targetId});
        if (target) {
            await target.remove();
            return true;
        } else {
            return false;
        }
    } else if (opt.url) {
        target = await Routes.findOne({url: opt.url});
        if (target) {
            await target.remove();
            return true;
        } else {
            return false;
        }
    }
};


//更新分类下的统计数量
const updateClassCounter = async (oldCateId, newCateId) => {
    if (oldCateId !== newCateId) {
        let oldcate = await ArticleClass.findOne({_id: oldCateId});
        let nowcate = await ArticleClass.findOne({_id: newCateId});
        oldcate.counter--;
        nowcate.counter++;
        await oldcate.save();
        await nowcate.save();
        return {
            status: true,
            msg: '更新分类统计成功~'
        }
    } else {
        return {
            status: true,
            msg: '分类信息未发生改变'
        }
    }
};


const getTime = function () {
    return new Date().getTime();
};
module.exports = router;
